<template>
  <div class="component-library">
    <div v-for="group in componentGroups" :key="group.name" class="component-group">
      <h4>{{ group.name }}</h4>
      <div
        v-for="component in group.components"
        :key="component.type"
        class="component-item"
        draggable="true"
        @dragstart="handleDragStart($event, component)"
      >
        <el-icon><component :is="component.icon || 'Menu'" /></el-icon>
        <span>{{ component.label }}</span>
      </div>
    </div>

    <!-- 自定义组件区域 -->
    <div class="component-group custom-components-group" v-if="customComponents.length > 0">
      <h4>
        自定义组件
        <el-tooltip content="管理自定义组件" placement="top">
          <el-button 
            type="primary" 
            size="small" 
            class="manage-btn" 
            circle 
            @click="openComponentManager"
          >
            <el-icon><Setting /></el-icon>
          </el-button>
        </el-tooltip>
      </h4>
      <div
        v-for="component in customComponents"
        :key="component.id"
        class="component-item custom-component-item"
        draggable="true"
        @dragstart="handleCustomDragStart($event, component)"
      >
        <el-icon><component :is="component.icon || 'Paperclip'" /></el-icon>
        <span>{{ component.label }}</span>
      </div>
    </div>

    <!-- 底部添加自定义组件按钮 -->
    <div class="add-custom-component">
      <el-button 
        type="primary" 
        size="small" 
        @click="openComponentImporter"
        :icon="Plus"
      >添加自定义组件</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import * as ElementPlusIconsVue from '@element-plus/icons-vue'; // 引入所有 Element Plus 图标
import { useDesignStore } from '../stores/designStore'; // <--- 引入 Store
import componentLoader from '../utils/componentLoader'; // 引入组件加载器
import { Setting, Plus } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';

// <--- 使用 Store
const designStore = useDesignStore();

// 定义组件数据结构接口 (可选，但推荐)
interface ComponentDefinition {
  type: string; // 对应将来要渲染的组件类型，如 'el-button'
  label: string; // 在库中显示的名称
  icon?: string; // 可选：Element Plus 图标名称
  // 可以添加默认 props 等
  defaultProps?: Record<string, any>;
}

// 自定义组件接口
interface CustomComponent {
  id: string;
  label: string;
  type: string;
  icon?: string;
}

interface ComponentGroup {
  name: string;
  components: ComponentDefinition[];
}

// 模拟组件列表数据 (基于 readme.md)
const componentGroups = ref<ComponentGroup[]>([
  {
    name: '基础组件',
    components: [
      // { type: 'title-bar', label: '标题栏', icon: 'FullScreen' }, // 标题栏比较特殊，后面单独处理
      { type: 'el-button', label: '按钮', icon: 'Pointer', defaultProps: { buttonText: '按钮' } }, // 对应配置的 buttonText
      { type: 'el-input', label: '输入框', icon: 'EditPen', defaultProps: { placeholder: '请输入...' } },
      { type: 'span', label: '文本', icon: 'Document', defaultProps: { textContent: '文本标签' } }, // 对应配置的 textContent
      { type: 'el-switch', label: '开关', icon: 'SwitchButton' },
      { type: 'el-slider', label: '滑块', icon: 'Sort' },
      { type: 'el-rate', label: '评分', icon: 'Star' },
      { type: 'el-tag', label: '标签', icon: 'Bookmark' },
      // ++ Use Group types defined in config
      { 
        type: 'el-radio-group', 
        label: '单选框组', 
        icon: 'List', 
        // No default props here, default children will be handled by store/config
      }, 
      { 
        type: 'el-checkbox-group', 
        label: '复选框组', 
        icon: 'Finished', 
        // No default props here, default children will be handled by store/config
      }, 
      { type: 'el-select', label: '下拉框', icon: 'ArrowDownBold' },
      // -- Keep individual radio/checkbox for direct use if needed --
      // { 
      //   type: 'el-radio', 
      //   label: '单选按钮', 
      //   icon: 'CircleCheck', 
      //   defaultProps: { label: '选项1', textContent: '选项文本1' } // 添加默认 props
      // },
      // { 
      //   type: 'el-checkbox', 
      //   label: '复选框', 
      //   icon: 'Check', 
      //   defaultProps: { label: '选项1', textContent: '选项文本1' } // 添加默认 props
      // },
    ],
  },
  {
    name: '容器组件',
    components: [
      { type: 'el-row', label: '行布局', icon: 'Rank' }, // Flex 横向
      { type: 'div', label: '列布局', icon: 'Operation' }, // Flex 纵向 (可以用普通 div + 样式实现)
      { type: 'el-card', label: '卡片', icon: 'CreditCard' },
    ],
  },
  {
    name: '数据展示',
    components: [
      { type: 'el-progress', label: '进度条', icon: 'TrendCharts' },
      { type: 'el-image', label: '图片', icon: 'Picture' },
      { type: 'el-divider', label: '分割线', icon: 'SplitCells' },
    ],
  },
  // 高级组件暂时省略
]);

// 自定义组件列表
const customComponents = ref<CustomComponent[]>([]);

// 在组件挂载时，从组件加载器获取自定义组件
onMounted(() => {
  updateCustomComponentsList();
  
  // 添加组件注册表变更监听
  componentLoader.addRegistryListener(updateCustomComponentsFromRegistry);
});

// 从组件注册表更新自定义组件列表
const updateCustomComponentsFromRegistry = () => {
  const registry = componentLoader.getRegistry();
  
  customComponents.value = Object.entries(registry)
    .filter(([_, comp]) => !comp.isBuiltIn) // 只显示非内置组件
    .map(([id, comp]) => ({
      id,
      label: comp.name,
      type: comp.type,
      icon: comp.icon
    }));
};

// 更新自定义组件列表
const updateCustomComponentsList = () => {
  updateCustomComponentsFromRegistry();
};

// 处理拖拽开始事件
const handleDragStart = (event: DragEvent, component: ComponentDefinition) => {
  // 调用 store action 设置拖拽状态
  designStore.setDraggingState(true); // <--- 设置拖拽状态为 true
  console.log('[LeftPanel DragStart] Setting isDraggingComponent to true.');

  if (event.dataTransfer) {
    // 准备拖拽数据，包含 action 和组件定义
    const dragData = {
      action: 'add', // <--- 明确添加 action 字段
      ...component // 展开 component 的所有属性 (type, label, defaultProps 等)
    };
    // 将包含 action 的数据存入 dataTransfer
    event.dataTransfer.setData('application/json', JSON.stringify(dragData));
    event.dataTransfer.effectAllowed = 'copy'; // 设置效果为复制
    console.log('[LeftPanel DragStart] Setting dataTransfer:', dragData);
  }
};

// 处理自定义组件拖拽开始事件
const handleCustomDragStart = (event: DragEvent, component: CustomComponent) => {
  // 调用 store action 设置拖拽状态
  designStore.setDraggingState(true);
  console.log('[LeftPanel CustomDragStart] Setting isDraggingComponent to true.');

  if (event.dataTransfer) {
    // 获取组件初始配置
    const initialInstance = componentLoader.createInitialInstance(component.id);
    
    if (!initialInstance) {
      console.error('无法创建组件初始实例:', component.id);
      return;
    }

    // 准备拖拽数据
    const dragData = {
      action: 'add',
      type: component.type,
      label: component.label,
      customComponentId: component.id,
      ...initialInstance
    };

    event.dataTransfer.setData('application/json', JSON.stringify(dragData));
    event.dataTransfer.effectAllowed = 'copy';
    console.log('[LeftPanel CustomDragStart] Setting dataTransfer:', dragData);
  }
};

// 打开组件导入对话框
const openComponentImporter = () => {
  ElMessageBox.alert(
    `组件导入功能正在开发中，将支持从以下路径导入组件：
    - 项目根目录的 dynamic-components 文件夹
    - 用户选择的本地 .vue 文件
    
    您也可以直接将 .vue 组件文件放入 dynamic-components 文件夹，系统将自动检测并加载。`, 
    '导入自定义组件', 
    {
      confirmButtonText: '确定',
      type: 'info',
    }
  );
};

// 打开组件管理器
const openComponentManager = () => {
  ElMessageBox.alert(
    '组件管理功能正在开发中，将支持：\n- 查看已加载组件详情\n- 卸载组件\n- 更新组件', 
    '管理自定义组件', 
    {
      confirmButtonText: '确定',
      type: 'info',
    }
  );
};

// 将所有图标注册到 Vue 实例，以便在模板中使用
// 注意：在实际大型项目中，可能需要按需引入图标
const icons = ElementPlusIconsVue;

</script>

<style scoped>
.component-library {
  padding: 10px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.component-group {
  margin-bottom: 15px;
}

.component-group h4 {
  font-size: 14px;
  color: #303133;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.component-item {
  display: flex;
  align-items: center;
  padding: 8px 10px;
  margin-bottom: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #fff;
  cursor: grab;
  transition: background-color 0.2s, box-shadow 0.2s;
}

.component-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.component-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #409eff;
}

.component-item span {
  font-size: 13px;
  color: #606266;
}

.custom-component-item {
  border-left: 3px solid #67c23a;
}

.add-custom-component {
  margin-top: auto;
  padding: 15px 0;
  text-align: center;
  border-top: 1px solid #eee;
}

.manage-btn {
  padding: 4px;
  font-size: 12px;
}
</style> 